/*
 * @Author: zhangjun 
 * @Date: 2017-06-06 15:13:55 
 * @Last Modified by: zhangjun
 * @Last Modified time: 2017-06-07 18:37:28
 */

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import App from './App';
import router from './router';

import axios from 'axios';
import store from './vuex/store';
import Vuex from 'vuex';

import Mint from 'mint-ui';
import 'mint-ui/lib/style.css';
// import 'flex.css';
import 'weui/dist/style/weui.min.css';
import weui from 'weui';
import { Toast } from 'mint-ui';

Vue.use(Mint);

import './filters';

Vue.config.productionTip = false;
axios.defaults.timeout = 1000 * 15;

Vue.config.errorHandler = function (err, vm) {
    var componentName = Vue.util.formatComponentName(vm),
        propsData = vm.$options.propsData;
    fundebug.notifyError(err, {
        metaData: {
            componentName: componentName,
            propsData: propsData
        }
    });
}


// 这里的config包含每次请求的内容

axios.interceptors.request.use(function (config) {
    if (store.getters.getToken) {
        config.headers.token = `${store.getters.getToken}`;
    }
    return config;
}, function (err) {
    return Promise.reject(err);
});

function globalErrorHandler(config, data) {
    if (!config.silence) {
        if (config.globalError) {
            config.globalError(data);
        }
        else if (data.message) {
            app.$Toast({
                message: `code:${data.code}, message:${data.message}`,
                position: 'top',
                duration: 5000
            });
        }
    }
}

axios.interceptors.response.use(res => {
    const { config, data } = res;
    const result = data || {};
    if ({}.hasOwnProperty.call(data, 'code')) {
        switch (data.code) {
            case 1:
                return res;
            default:
                globalErrorHandler(config, data);
                return Promise.reject(data);
        }
    }
}, error => Promise.reject(error));


Vue.prototype.$http = axios;
Vue.prototype.$weui = weui;
Vue.prototype.$Toast = Toast;

/* eslint-disable no-new */
var app = new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app');

export default app;